package de.poketradeshop.ui.controller;

import java.io.Serializable;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import de.poketradeshop.database.DatabaseService;
import de.poketradeshop.ui.model.Customer;
import de.poketradeshop.ui.model.CustomerSession;
import de.poketradeshop.ui.model.Order;
import de.poketradeshop.ui.model.OrderContainer;
import de.poketradeshop.ui.model.Product;
import de.poketradeshop.ui.service.MailService;

@Named
@SessionScoped
public class OrderController implements Serializable {

	@Inject
	private Order order;

	@Inject
	private OrderContainer orderContainer;

	@Inject
	private DatabaseService databaseService;

	@Inject
	private CustomerSession customerSession;

	@Inject
	private Customer customer;

	/**
	 * Initiate orders
	 */
	public void initiateOrderTiles() {
		try {
			// Get all orders from Database by Custommer ID
			List<Order> allOrders = databaseService.getOrdersList(customerSession.getCustomerId());
			//Add to order container
			orderContainer.setOrders(allOrders);

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * Adds a chosen product to order/basket
	 * @param product
	 */
	public void addProductToOrder(Product product) {
		Order o = new Order();

		o.setBasket(true);
		o.setPokemonId(product.getId());
		o.setPokemonLevel(product.getLevel());
		o.setPokemonName(product.getName());
		o.setPokemonType1(product.getType1());
		o.setPokemonType2(product.getType2());
		o.setProductId(product.getProductId());
		o.setShiny(product.isShiny());

		//check if product has a special price and set it
		if (product.getSpecialPrice() != 0.0) {
			o.setTotalAmount(product.getSpecialPrice());
		} else {
			o.setTotalAmount(product.getNormalPrice());
		}


		//set total amount of order
		order.setTotalRealAmount(order.getTotalRealAmount() + o.getTotalAmount());
		
		product.setInBasket(true);
		orderContainer.getOrders().add(o);
		}
	
	/**
	 * Delete order from basket
	 * @param productId
	 * @return String
	 */
	public String removeProductFromOrder(int productId) {
		for (int i = 0; i < orderContainer.getOrders().size(); i++) {
			Order check = orderContainer.getOrders().get(i);

			if (check.getProductId() == productId) {
				orderContainer.getOrders().remove(check);
				order.setTotalRealAmount(Math.abs(order.getTotalRealAmount() - check.getTotalAmount()));
			}
		}

		return "checkout.xhtml";
	}


	/**
	 * Complete Order
	 * @return String
	 */
	public String completeOrder() {
		try {

			//Set date format

			if (orderContainer.getOrders().isEmpty()) {

				FacesContext.getCurrentInstance().addMessage(
						"cart:buy",
						new FacesMessage(FacesMessage.SEVERITY_ERROR, "Fehler",
								"Ihr Warenkorb enthält keine Produkte"));

				return "";
			}

			for (int i = 0; i < orderContainer.getOrders().size(); i++) {

				Order check = orderContainer.getOrders().get(i);

				if ((databaseService.checkOrderAvailability(check.getProductId())) == false) {
					
					FacesContext.getCurrentInstance().addMessage(
							"cart:buy",
							new FacesMessage(FacesMessage.SEVERITY_ERROR, "Fehler",
									"Das Pokemon " + check.getPokemonName() + " wurde leider in der Zwischenzeit schon gekauft."
											+ " Wenn Sie mit dem Kauf fortführen möchte, müssen Sie den Artikel aus Ihrem Warenkorb entfernen."));
					
					return "";
				}

			}


			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar cal = Calendar.getInstance();

			//set date
			String date = dateFormat.format(cal.getTime()).substring(0, 10);
			//set time
			String time = dateFormat.format(cal.getTime()).substring(11);

			//clear previous mail from same session
			MailService.clearMail();
			
			//go through order container 
			for (int i = 0; i < orderContainer.getOrders().size(); i++) {
				Order insert = orderContainer.getOrders().get(i);

				//set order in database
				databaseService.completeOrder(customerSession.getCustomerId(),
						insert.getProductId(), insert.getTotalAmount(), date, time);

				//add product name to mail 
				MailService.fillMail("Produkt Nr.: " + insert.getProductId() + "<br/>Pokemon: #" + insert.getPokemonId() + " - " 
				+ insert.getPokemonName() + "<br/>Level: " + insert.getPokemonLevel() + "<br/>Preis: " + String.format("%.2f", insert.getTotalAmount()) + " &euro;");
			}

			//add total amount to mail
			MailService.fillMailValue("Gesamtpreis: " + String.format("%.2f", order.getTotalRealAmount()) + " &euro;");
			
			//clear order container
			orderContainer.getOrders().clear();
			order.setTotalRealAmount(0);


			//System.out.println(customer.getEmail());
			//Send email with order confirmation
			MailService.sendMessageOrder(customer.getEmail());

			return "checkoutComplete.xhtml";

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "";
	}

}
